import React, { useState, forwardRef, useImperativeHandle } from 'react'
import { Form, Input, Modal } from 'antd';
import { addUsers,updateUsers} from '../../../api/user';
function AddOrUpdate(props: any, ref: any) {
    //  用户id为0时则表示添加用户
    let [userId,setUserId] = useState(0);
    // 定义对话框是否显示状态
    let [isModalOpen, setIsModalOpen] = useState(false);
    // form表单组件实例
    let [form] = Form.useForm();
    // 点击确认回调
    let handleOk = () => {
        console.log(form)
        // 进行表单验证
        form.validateFields().then(async (value:AddUserData) => {
            if(userId!==0){
                // 编辑用户
                let res = await updateUsers(value,userId);
                if(res.data.meta.status!==200){
                    return
                }
                   // 重置表单并隐藏模态框
                   form.resetFields();
                   setIsModalOpen(false)
                   // 子组件告诉父组件添加成功
                   props.over();
                return
            }
            // 发送请求 添加用户
            let res = await addUsers(value);
            if(res.data.meta.status===201){
                // 重置表单并隐藏模态框
                form.resetFields();
                setIsModalOpen(false)
                // 子组件告诉父组件添加成功
                props.over();
            }
        }).catch(err => {
            console.log(err)
        })
    }
    //点击取消的回调
    let handleCancel = () => {
         // 重置表单并隐藏模态框
         form.resetFields();
        setIsModalOpen(false)
    }
    //  子组件初始化方法
    let init = (record:DataTable | undefined) => {
        setIsModalOpen(true)
        if(record){
            //编辑用户
            setUserId(record.id)
            // 设置当前编辑数据
            form.setFieldsValue({
                username:record.username,
                email:record.email,
                mobile:record.mobile
            })
        }else{
            //添加用户
            setUserId(0)
        }
    }
    // 将子组件init方法暴露给父组件ref
    useImperativeHandle(ref, () => {
        return {
            init
        }
    })
    const layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
    };
    return (
        <Modal title={userId===0?'添加用户':'编辑用户'} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} okText={userId===0?'确认添加':'确认编辑'} cancelText={'取消'}>
            <Form
                form={form}
                style={{ maxWidth: 600 }}
                {...layout}
            >
                <Form.Item name="username" label="用户名"  rules={[
                    {
                        required: true, message: "请输入用户名"
                    }
                ]}>
                    <Input disabled={userId!==0} />
                </Form.Item>
                {
                    userId===0 && <Form.Item name="password" label="密码" rules={[
                        {
                            required:userId===0, message: "请输入密码"
                        }
                    ]}>
                        <Input />
                    </Form.Item>
                }
                <Form.Item name="email" label="邮箱" rules={[
                    {
                        required: true, message: "请输入邮箱"
                    }, {
                        type: 'email', message: "请输入正确的邮箱"
                    }
                ]}>
                    <Input />
                </Form.Item>
                <Form.Item name="mobile" label="手机号" rules={[
                    {
                        required: true, message: "请输入手机号"
                    }, {
                        // pattern: ,
                        message: "请输入正确的手机号",
                        // 自定义校验
                        validator:(_,value)=>{
                            let test = /^[1][3,4,5,7,8,9][0-9]{9}$/;
                            if(test.test(value)){
                               return Promise.resolve() 
                            }else{
                               return  Promise.reject(new Error('请输入正确的手机号'))  
                            }
                        }
                    }
                ]}>
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    )
}
export default forwardRef(AddOrUpdate);
